package com.pro01.backend.controller;

import com.pro01.backend.dto.PostDetailDTO;
import com.pro01.backend.dto.PostSummaryDTO;
import com.pro01.backend.pojo.Forum2Post;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.Forum2PostService;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/forum2")
public class Forum2PostController {

    @Autowired
    private Forum2PostService postService;

    // 发帖接口：POST /forum2/sections/{section}/posts
    @PostMapping("/sections/{section}/posts")
    public Result<Map<String, Object>> createPost(@PathVariable("section") String section,
                                                  @RequestBody Forum2Post post,
                                                  HttpServletRequest request) {
        Long userId = TokenUtil.getUserId(request);

        if (post.getTitle() == null || post.getTitle().trim().isEmpty()) {
            return Result.error("标题不能为空");
        }
        if (post.getContent() == null || post.getContent().trim().isEmpty()) {
            return Result.error("内容不能为空");
        }

        post.setUserId(userId);
        post.setSection(section);
        int result = postService.createPost(post);

        if (result > 0) {
            // ✅ 返回 section 信息
            Map<String, Object> data = new HashMap<>();
            data.put("section", section);
            return Result.success(data);
        } else {
            return Result.error("发帖失败");
        }
    }

    // 用户查看帖子列表
    @GetMapping("/sections/{section}/posts")
    public Result<PageResult<PostSummaryDTO>> getPostsBySection(@PathVariable("section") String section,
                                                                @RequestParam(defaultValue = "1") int pageNum,
                                                                @RequestParam(defaultValue = "10") int pageSize) {
        PageResult<PostSummaryDTO> result = postService.getPostsBySection(section, pageNum, pageSize);
        return Result.success(result);
    }

    // 用户查看帖子详情
//    @GetMapping("/posts/{postId}")
//    public Result<PostDetailDTO> getPostDetail(@PathVariable Long postId) {
//        PostDetailDTO detail = postService.getPostDetail(postId);
//        if (detail == null) {
//            return Result.error("帖子不存在或已被删除");
//        }
//        return Result.success(detail);
//    }
    @GetMapping("/posts/{postId}")
    public Result<PostDetailDTO> getPostDetail(@PathVariable Long postId,
                                               HttpServletRequest request) {
        Long userId = TokenUtil.getUserId(request);
        PostDetailDTO detail = postService.getPostDetail(postId, userId);
        if (detail == null) {
            return Result.error("帖子不存在或已被删除");
        }
        return Result.success(detail);
    }


    // 用户删除帖子
    @DeleteMapping("/posts/{postId}")
    public Result<Void> deletePost(@PathVariable Long postId,
                                   HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            String role = TokenUtil.getRole(request);
            int result = postService.deletePost(postId, userId, role);
            return result > 0 ? Result.success() : Result.error("删除失败");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 用户隐藏帖子
    @PutMapping("/posts/{postId}/hide")
    public Result<Void> hidePost(@PathVariable Long postId, HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            String role = TokenUtil.getRole(request);
            int result = postService.hidePost(postId, userId, role);
            return result > 0 ? Result.success() : Result.error("隐藏失败");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 用户显示帖子
    @PutMapping("/posts/{postId}/unhide")
    public Result<Void> unhidePost(@PathVariable Long postId, HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            String role = TokenUtil.getRole(request);
            int result = postService.unhidePost(postId, userId, role);
            return result > 0 ? Result.success() : Result.error("显示失败");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 模糊查询帖子
    @GetMapping("/posts/search")
    public Result<PageResult<PostSummaryDTO>> searchPosts(@RequestParam String keyword,
                                                          @RequestParam(defaultValue = "1") int pageNum,
                                                          @RequestParam(defaultValue = "10") int pageSize) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return Result.error("关键词不能为空");
        }
        PageResult<PostSummaryDTO> result = postService.searchPosts(keyword.trim(), pageNum, pageSize);
        return Result.success(result);
    }

    // 推荐系统
    @GetMapping("/posts/recommend")
    public Result<Map<String, PostSummaryDTO>> getRecommendedPosts() {
        Map<String, PostSummaryDTO> map = postService.getRecommendedPosts();
        return Result.success(map);
    }


}

